package utilities;

import controllers.C_Control;

public class EventOwner extends C_Control
{
  EventListener[] subscribers = new EventListener[0];
  
  public void addSubscriber(EventListener scribe)
  {
	  EventListener[] tmpList = subscribers; // create a copy of the list
	  subscribers = new EventListener[subscribers.length+1]; // make room for new element
	  for(int i = 0; i < tmpList.length; i++) {
		subscribers[i] = tmpList[i]; // add the elements back in
	  }
	  subscribers[tmpList.length] = scribe; // add the new element to the end   
	  //subscribers = (EventListener[])append(subscribers, scribe); 
  }
  
  public void removeSubscriber(EventListener scribe)
  {
    for(int i = 0; i < subscribers.length; i++)
    {
      if(subscribers[i].equals(scribe))
      {
        EventListener[] tmpList = subscribers;
        subscribers = new EventListener[tmpList.length-1];
        int s = 0;
        for(int e = 0; e < tmpList.length; e++)
        {
          if(e != i) subscribers[e-s] = tmpList[e];
          else s = 1; // compensate for index going out of bounds
        }
        return;
      }
    }
  }
  
  // send the scripted trigger keyword to all subscribers (EventListeners)
  protected void triggerEvent(String trigger)
  {
    for(int i = 0; i < subscribers.length; i++)
    {
      subscribers[i].handleEvent(trigger, this); 
    }
  }
}
